<template>
	<div ref="zhEcharts" :style="{ height: height, width: width }"></div>
</template>

<script lang="ts">
import * as echarts from 'echarts';
export default defineComponent({
	name: 'zhEcharts',
	props: {
		height: { type: String, default: '100%' },
		width: { type: String, default: '100%' },
		option: { type: Object, default: () => {} },
	},
	setup(props) {
		const { proxy } = <any>getCurrentInstance();
		const state = reactive({
			nodata: true,
		});

		let isActivat = false;
		let zhChart: echarts.ECharts | null = null;
		//监听传入的参数
		watch(
			() => props.option,
			(value) => {
				if (zhChart) {
					zhChart.setOption(value, true);
				}
			},
			{
				deep: true,
			}
		);
		// 监听 vuex 中的 tagsview 开启全屏变化，重新 resize 图表，防止不出现/大小不变等
		watch(
			() => $store.tagsView.isTagsViewCurrenFull,
			() => {
				eventListener();
			}
		);
		const myOptions = computed(() => {
			return props.option || {};
		});
		const initEcharts = () => {
			if (!zhChart) {
				const dom: any = proxy.$refs.zhEcharts;
				zhChart = echarts.init(dom);
			} else {
				return;
			}
			zhChart.setOption(myOptions.value);
			window.addEventListener('resize', eventListener);
		};
		const eventListener = () => {
			if (zhChart) {
				zhChart.resize();
			}
		};
		//页面缓存原因重新处理表格大小
		onActivated(() => {
			if (!isActivat) {
				nextTick(() => {
					if (zhChart) {
						zhChart.resize();
					}
				});
			}
		});
		onDeactivated(() => {
			isActivat = false;
		});
		onMounted(() => {
			isActivat = true;
			nextTick(() => {
				initEcharts();
			});
		});
		onBeforeUnmount(() => {
			window.removeEventListener('resize', eventListener);
		});

		return {
			...toRefs(state),
		};
	},
});
</script>
